package com.cheney.demo.algorithm;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author si.chen
 * @date 2021/6/20 21:50
 */
public class LruDemo<k, v> extends LinkedHashMap<k, v> {

    private int capacity;

    public LruDemo() {
    }

    /**
     * acessOrder true 访问顺序  false插入顺序
     */
    public LruDemo(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<k, v> eldest) {
        return super.size() > capacity;
    }

    public static void main(String[] args) {
        LruDemo demo = new LruDemo(3);
        demo.put("1", "a");
        demo.put("2", "b");
        demo.put("3", "c");
        System.out.println(demo.keySet());
        demo.put("4", "d");
        System.out.println(demo.keySet());
        demo.put("3", "c");
        System.out.println(demo.keySet());
        demo.put("3", "c");
        System.out.println(demo.keySet());
        demo.put("3", "c");
        System.out.println(demo.keySet());
        demo.put("5", "x");
        System.out.println(demo.keySet());
    }
}
